package e151;

import javax.swing.*;

public class PrimeThread implements Runnable{
	JTextField gs1fld,gs2fld,gsfld;
	int value,gs1,gs2,gs,mid;
	boolean flag1,flag2;
	Thread thread1,thread2,thread3;
	PrimeThread(JTextField f1,JTextField f2,JTextField f3){
		value=0; gs1=0; gs2=0; gs=0;
		thread1=new Thread(this);
		thread2=new Thread(this);
		thread3=new Thread(this);
		flag1=true; flag2=true;
		gs1fld=f1; gs2fld=f2; gsfld=f3;
	}
	void setValue(int v) {
		value=v;
		mid=value/2;
	}
	boolean isPrime(int x) {
		if (x<2) return false;
		for (int i=2; i<x; i++)
			if (x%i==0)
				return false;
		return true;
	}
	public void run() {
		Thread t;
		t=Thread.currentThread();
		//System.out.println(t);
		if (t==thread1) {
			
				for (int i=2; i<=mid; i++)
					try {
					if (t.interrupted()) {
						
						break;
					}
					else
						if (isPrime(i)) {
							gs1++; //System.out.println("1:"+gs1);
							gs1fld.setText(String.valueOf(gs1));
						}
					}
					catch (Exception e) {}
				flag1=false;
				//System.out.println("1:"+flag1);
			
		}
		if (t==thread2){
			
			
				for (int i=mid+1; i<=value; i++)
				try {	
					if (t.interrupted()){
						
						break;
					}
						
					else
						if (isPrime(i)) {
							gs2++; //System.out.println("2:"+gs2);
							gs2fld.setText(String.valueOf(gs2));
						}
				}
				catch (Exception e) {}
				flag2=false;
				//System.out.println("2:"+flag2);
			
		}
		if (t==thread3){
			
			
				while (true) {
					//System.out.println("3:");
					try {
					if (t.interrupted()){
						
						break;
					}
						
					else
						if (flag1==false && flag2==false) {
							gs=gs1+gs2; //System.out.println("3:"+gs);
							gsfld.setText(String.valueOf(gs));
							break;
						}
					}
					catch (Exception e) {}
				}
			
		}
	}
	
}
